//
//  SliderViewController.m
//  TestSlider
//
//  Created by gaokunpeng on 15/4/11.
//  Copyright (c) 2015年 . All rights reserved.
//

#import "SliderViewController.h"
#import <sys/utsname.h>
#import "CalendarViewController.h"

typedef NS_ENUM(NSInteger, RMoveDirection) {
    RMoveDirectionLeft = 0,
    RMoveDirectionRight
};
static BOOL isOk = NO;

static SliderViewController *sharedSVC=nil;
@interface SliderViewController ()<UIGestureRecognizerDelegate>{
//    UIView *_mainContentView;
    UIView *_leftSideView;
    UIView *_rightSideView;
    
    NSMutableDictionary *_controllersDict;
    
//    UITapGestureRecognizer *_tapGestureRec;
//    UIPanGestureRecognizer *_panGestureRec;
    
    BOOL showingLeft;
    BOOL showingRight;
}

@end

@implementation SliderViewController

-(void)dealloc{
#if __has_feature(objc_arc)
    _mainContentView = nil;
    _leftSideView = nil;
    _rightSideView = nil;
    
    _controllersDict = nil;
    
    _tapGestureRec = nil;
    _panGestureRec = nil;
    
    _LeftVC = nil;
    _RightVC = nil;
    _MainVC = nil;
#else
    [_mainContentView release];
    [_leftSideView release];
    [_rightSideView release];
    
    [_controllersDict release];
    
    [_tapGestureRec release];
    [_panGestureRec release];
    
    [_LeftVC release];
    [_RightVC release];
    [_MainVC release];
    [super dealloc];
#endif
    
}

+ (id)sharedSliderController
{
    
    //    static dispatch_once_t onceToken;
    //    dispatch_once(&onceToken, ^{
    //        sharedSVC = [[self alloc] init];
    //    });
    if (sharedSVC==nil) {
        sharedSVC=[[self alloc]init];
    }
    isOk = NO;
    return sharedSVC;
}
-(void)releaseClick{
    sharedSVC=nil;
}
- (id)initWithCoder:(NSCoder *)decoder {
    if ((self = [super initWithCoder:decoder])) {
        _LeftSContentOffset=160;
        _RightSContentOffset=160;
        _LeftSContentScale=0.85;
        _RightSContentScale=0.85;
        _LeftSJudgeOffset=100;
        _RightSJudgeOffset=100;
        _LeftSOpenDuration=0.3;
        _RightSOpenDuration=0.4;
        _LeftSCloseDuration=0.3;
        _RightSCloseDuration=0.3;
        _canShowLeft=YES;
        _canShowRight=YES;
    }
    return self;
}

- (id)init{
    if (self = [super init]){
        _LeftSContentOffset=160;
        _RightSContentOffset=160;
        _LeftSContentScale=0.85;
        _RightSContentScale=0.85;
        _LeftSJudgeOffset=100;
        _RightSJudgeOffset=100;
        _LeftSOpenDuration=0.3;
        _RightSOpenDuration=0.4;
        _LeftSCloseDuration=0.3;
        _RightSCloseDuration=0.3;
        _canShowLeft=YES;
        _canShowRight=YES;
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationController.navigationBarHidden=YES;
    
    _controllersDict = [[NSMutableDictionary alloc] init];
    
    [self initSubviews];
    
    [self initChildControllers:_LeftVC rightVC:_RightVC];
    
    [self showContentControllerWithModel:_MainVC!=nil?NSStringFromClass([_MainVC class]):@"MainViewController"];
    
    //    if((self.wantsFullScreenLayout=_MainVC.wantsFullScreenLayout)){
    //        _rightSideView.frame=[UIScreen mainScreen].bounds;
    //        _leftSideView.frame=[UIScreen mainScreen].bounds;
    //        _mainContentView.frame=[UIScreen mainScreen].bounds;
    //    }
    
    _tapGestureRec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeSideBar)];//关闭
    _tapGestureRec.delegate=self;
    [_mainContentView addGestureRecognizer:_tapGestureRec];
    _tapGestureRec.enabled = NO;//禁用了点击手势
    
    _panGestureRec = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(moveViewWithGesture:)];//滑动
    [_mainContentView addGestureRecognizer:_panGestureRec];//添加滑动手势
    if (isOk)
    {//如果是YES，说明需要隐藏
        _panGestureRec.enabled = NO;
    }
//    NSLog(@"3333:%lu",[[self view] gestureRecognizers].count);
//    NSLog(@"3332222:%lu",[_mainContentView gestureRecognizers].count);
}

//禁用侧滑手势
- (void)closePanGesttureRec
{
    _panGestureRec.enabled = NO;
    isOk = YES;//标记量为YES
}
//开启侧滑手势
- (void)openPanGesttureRec
{
    _panGestureRec.enabled = YES;
    isOk = NO;//标记量为NO
}

#pragma mark - Init

- (void)initSubviews
{
    _rightSideView = [[UIView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:_rightSideView];
    
    _leftSideView = [[UIView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:_leftSideView];
    
    _mainContentView = [[UIView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:_mainContentView];
    
}

- (void)initChildControllers:(UIViewController*)leftVC rightVC:(UIViewController*)rightVC
{
    if (_canShowRight&&rightVC!=nil) {
        [self addChildViewController:rightVC];
        rightVC.view.frame=CGRectMake(0, 0, rightVC.view.frame.size.width, rightVC.view.frame.size.height);
        [_rightSideView addSubview:rightVC.view];
    }
    if (_canShowLeft&&leftVC!=nil) {
        [self addChildViewController:leftVC];
        leftVC.view.frame=CGRectMake(0, 0, leftVC.view.frame.size.width, leftVC.view.frame.size.height);
        [_leftSideView addSubview:leftVC.view];
    }
}

#pragma mark - Actions

- (void)showContentControllerWithModel:(NSString *)className
{
    [self closeSideBar];
    
    UIViewController *controller = _controllersDict[className];
    if (!controller)
    {
        Class c = NSClassFromString(className);
        
#if __has_feature(objc_arc)
        controller = [[c alloc] init];
#else
        controller = [[[c alloc] init] autorelease];
#endif
        [_controllersDict setObject:controller forKey:className];
    }
    
    if (_mainContentView.subviews.count > 0)
    {
        UIView *view = [_mainContentView.subviews firstObject];
        [view removeFromSuperview];
    }
    
    controller.view.frame = _mainContentView.frame;
    [_mainContentView addSubview:controller.view];
    
    self.MainVC=controller;
}

- (void)showLeftViewController
{
    if (showingLeft) {
        [self closeSideBar];
        return;
    }
    if (!_canShowLeft||_LeftVC==nil) {
        return;
    }
    CGAffineTransform conT = [self transformWithDirection:RMoveDirectionRight];
    
    [self.view sendSubviewToBack:_rightSideView];
    [self configureViewShadowWithDirection:RMoveDirectionRight];
    
    [UIView animateWithDuration:_LeftSOpenDuration
                     animations:^{
                         _mainContentView.transform = conT;
                     }
                     completion:^(BOOL finished) {
                         _tapGestureRec.enabled = YES;
                         showingLeft=YES;
                         _MainVC.view.userInteractionEnabled=NO;
                     }];
}

- (void)showRightViewController
{
    if (showingRight) {
        [self closeSideBar];
        return;
    }
    if (!_canShowRight||_RightVC==nil) {
        return;
    }
    CGAffineTransform conT = [self transformWithDirection:RMoveDirectionLeft];
    
    [self.view sendSubviewToBack:_leftSideView];
    [self configureViewShadowWithDirection:RMoveDirectionLeft];
    
    [UIView animateWithDuration:_RightSOpenDuration
                     animations:^{
                         _mainContentView.transform = conT;
                     }
                     completion:^(BOOL finished) {
                         _tapGestureRec.enabled = YES;
                         showingRight=YES;
                         _MainVC.view.userInteractionEnabled=NO;
                     }];
}

- (void)closeSideBar
{
    [self closeSideBarWithAnimate:YES complete:^(BOOL finished) {}];
}

- (void)closeSideBarWithAnimate:(BOOL)bAnimate complete:(void(^)(BOOL finished))complete
{
    CGAffineTransform oriT = CGAffineTransformIdentity;
    if (bAnimate)
    {
        [UIView animateWithDuration:_mainContentView.transform.tx==_LeftSContentOffset?_LeftSCloseDuration:_RightSCloseDuration
                         animations:^{
                             _mainContentView.transform = oriT;
                         }
                         completion:^(BOOL finished) {
                             _tapGestureRec.enabled = NO;
                             showingRight=NO;
                             showingLeft=NO;
                             _MainVC.view.userInteractionEnabled=YES;
                             complete(finished);
                         }];
    }else
    {
        _mainContentView.transform = oriT;
        _tapGestureRec.enabled = NO;
        showingRight=NO;
        showingLeft=NO;
        _MainVC.view.userInteractionEnabled=YES;
        complete(YES);
    }
}

- (void)moveViewWithGesture:(UIPanGestureRecognizer *)panGes
{//滑动
//    TJJLog(@"滑动触发");
    static CGFloat currentTranslateX;
    if (panGes.state == UIGestureRecognizerStateBegan)
    {
        currentTranslateX = _mainContentView.transform.tx;
//        TJJLog(@"开始x的坐标位置：%f",currentTranslateX);
    }
    if (panGes.state == UIGestureRecognizerStateChanged)
    {
        CGFloat transX = [panGes translationInView:_mainContentView].x;
        transX = transX + currentTranslateX;
        CGFloat sca=0;
//        TJJLog(@"transX = %f",transX);
        
        CGFloat ltransX = (transX - _LeftSContentOffset)/_LeftSContentOffset * _LeftContentViewSContentOffset;
//        TJJLog(@"ltransX = %f",ltransX);

        CGFloat lsca = 1;
        
        if (transX > 0)
        {//main的X坐标位置  左视图
            if (!_canShowLeft||_LeftVC==nil) {
                return;
            }
            
            [self.view sendSubviewToBack:_rightSideView];
            [self configureViewShadowWithDirection:RMoveDirectionRight];
            
            if (_mainContentView.frame.origin.x < _LeftSContentOffset)//_LeftSContentOffset =100
            {//向左滑判断
                sca = 1 - (_mainContentView.frame.origin.x/_LeftSContentOffset) * (1-_LeftSContentScale);
                lsca = 1 - sca + _LeftSContentScale;
            }
            else
            {//向右滑判断
                sca = _LeftSContentScale;
                lsca = 1;
                
                ltransX = 0;
            }
//            TJJLog(@"lsca=%f------ltransX=%f",lsca,ltransX);
            if (self.changeLeftView) {
                self.changeLeftView(lsca, ltransX);
            }
            
        }
        else    //transX < 0
        {//main的X坐标位置  右边视图（现在不用）
            if (!_canShowRight||_RightVC==nil) {
                return;
            }
            
            [self.view sendSubviewToBack:_leftSideView];
            [self configureViewShadowWithDirection:RMoveDirectionLeft];
            
            if (_mainContentView.frame.origin.x > -_RightSContentOffset)
            {
                sca = 1 - (-_mainContentView.frame.origin.x/_RightSContentOffset) * (1-_RightSContentScale);
            }
            else
            {
                sca = _RightSContentScale;
            }
        }
        CGAffineTransform transS = CGAffineTransformMakeScale(sca, sca);
        CGAffineTransform transT = CGAffineTransformMakeTranslation(transX, 0);
        CGAffineTransform conT = CGAffineTransformConcat(transT, transS);
        _mainContentView.transform = conT;
    }
    else if (panGes.state == UIGestureRecognizerStateEnded)
    {
        //SXW__添加，panX为+,则表示从左往右滑动。panX为负数，则表示从右往左滑动。
        CGFloat panX = [panGes translationInView:_mainContentView].x;
        //        CGFloat finalX = currentTranslateX + panX;
        CGFloat finalX = currentTranslateX + panX;
//        TJJLog(@"现在的X坐标，panx = %f ,,,开始X坐标currentTarnsX=%f,,最终X的坐标值：===%f",panX,currentTranslateX,finalX);
        if (panX > 0)
        {//从左边往右滑动
            if (finalX > SCREEN_WIDTH/3.0)//SCREEN_WIDTH/3.0*2   finalX > _LeftSJudgeOffset
            {//从左边向右滑动的距离大于3/1，就执行
                if (!_canShowLeft||_LeftVC==nil) {
                    return;
                }
                
                CGAffineTransform conT = [self transformWithDirection:RMoveDirectionRight];
                [UIView beginAnimations:nil context:nil];
                _mainContentView.transform = conT;
                [UIView commitAnimations];
                
                showingLeft=YES;
                _MainVC.view.userInteractionEnabled=NO;
                
                _tapGestureRec.enabled = YES;
                
                [self showLeft:YES];//显示左视图
                
                return;
            }
            else
            {
                CGAffineTransform oriT = CGAffineTransformIdentity;
                [UIView beginAnimations:nil context:nil];
                _mainContentView.transform = oriT;
                [UIView commitAnimations];
                
                [self showLeft:NO];
                
                showingRight=NO;
                showingLeft=NO;
                _MainVC.view.userInteractionEnabled=YES;
                _tapGestureRec.enabled = NO;
            }

        }
        else
        {//从右往左滑动
//            TJJLog(@"滑动占整个界面的宽度%f",-(-panX+SCREEN_WIDTH-_LeftSContentOffset));
            if (-(-panX+SCREEN_WIDTH-_LeftSContentOffset) < -SCREEN_WIDTH/3.0)
            {//从左边向右滑动的距离大于3/1，就执行
                CGAffineTransform oriT = CGAffineTransformIdentity;
                [UIView beginAnimations:nil context:nil];
                _mainContentView.transform = oriT;
                [UIView commitAnimations];
                
                [self showLeft:NO];
                
                showingRight=NO;
                showingLeft=NO;
                _MainVC.view.userInteractionEnabled=YES;
                _tapGestureRec.enabled = NO;
            }
            else
            {
                if (!_canShowLeft||_LeftVC==nil) {
                    return;
                }
                
                CGAffineTransform conT = [self transformWithDirection:RMoveDirectionRight];
                [UIView beginAnimations:nil context:nil];
                _mainContentView.transform = conT;
                [UIView commitAnimations];
                
                showingLeft=YES;
                _MainVC.view.userInteractionEnabled=NO;
                
                _tapGestureRec.enabled = YES;
                
                [self showLeft:YES];//显示左视图
                
                return;
            }
        }
//        CGFloat panX = [panGes translationInView:_mainContentView].x;
////        CGFloat finalX = currentTranslateX + panX;
//        CGFloat finalX = currentTranslateX + panX;
//        //X的起始坐标为0，则显示的是主界面
//        TJJLog(@"现在的X坐标，panx = %f ,,,开始X坐标currentTarnsX=%f,,最终X的坐标值：===%f",panX,currentTranslateX,finalX);
//        if (finalX > SCREEN_WIDTH/3.0)//SCREEN_WIDTH/3.0*2   finalX > _LeftSJudgeOffset
//        {//从左边向右滑动的距离大于3/1，就执行
//            if (!_canShowLeft||_LeftVC==nil) {
//                return;
//            }
//            
//            CGAffineTransform conT = [self transformWithDirection:RMoveDirectionRight];
//            [UIView beginAnimations:nil context:nil];
//            _mainContentView.transform = conT;
//            [UIView commitAnimations];
//            
//            showingLeft=YES;
//            _MainVC.view.userInteractionEnabled=NO;
//            
//            _tapGestureRec.enabled = YES;
//            
//            [self showLeft:YES];//显示左视图
//            
//            return;
//        }
//
//        
//        if (finalX < -SCREEN_WIDTH/3.0)//-_RightSJudgeOffset
//        {
//            if (!_canShowRight||_RightVC==nil) {
//                return;
//            }
//            
//            CGAffineTransform conT = [self transformWithDirection:RMoveDirectionLeft];
//            [UIView beginAnimations:nil context:nil];
//            _mainContentView.transform = conT;
//            [UIView commitAnimations];
//            
//            showingRight=YES;
//            _MainVC.view.userInteractionEnabled=NO;
//            
//            _tapGestureRec.enabled = YES;
//            
//            return;
//        }
//        else
//        {
//            CGAffineTransform oriT = CGAffineTransformIdentity;
//            [UIView beginAnimations:nil context:nil];
//            _mainContentView.transform = oriT;
//            [UIView commitAnimations];
//            
//            [self showLeft:NO];
//            
//            showingRight=NO;
//            showingLeft=NO;
//            _MainVC.view.userInteractionEnabled=YES;
//            _tapGestureRec.enabled = NO;
//        }
    }
}

#pragma mark -
- (void)showLeft:(BOOL)bShow
{
    if (bShow)
    {
        [UIView beginAnimations:nil context:nil];
        if (self.changeLeftView) {
            self.changeLeftView(1, 0);
        }
        
        [UIView commitAnimations];
    }else
    {
        [UIView beginAnimations:nil context:nil];
        if (self.changeLeftView) {
            self.changeLeftView(_LeftSContentScale, -_LeftContentViewSContentOffset);
        }
        
        [UIView commitAnimations];
    }
}

- (CGAffineTransform)transformWithDirection:(RMoveDirection)direction
{
    CGFloat translateX = 0;
    CGFloat transcale = 0;
    switch (direction) {
        case RMoveDirectionLeft:
            translateX = -_RightSContentOffset;
            transcale = _RightSContentScale;
            break;
        case RMoveDirectionRight:
            translateX = _LeftSContentOffset;//侧边栏宽度，这边是自己设置的273（320）的宽度。
            transcale = _LeftSContentScale;
            break;
        default:
            break;
    }
    
    CGAffineTransform transT = CGAffineTransformMakeTranslation(translateX, 0);
    CGAffineTransform scaleT = CGAffineTransformMakeScale(transcale, transcale);
    CGAffineTransform conT = CGAffineTransformConcat(transT, scaleT);
    
    return conT;
}

- (NSString*)deviceWithNumString{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    @try {
        return [deviceString stringByReplacingOccurrencesOfString:@"," withString:@""];
    }
    @catch (NSException *exception) {
        return deviceString;
    }
    @finally {
    }
}

- (void)configureViewShadowWithDirection:(RMoveDirection)direction
{
    if ([[self deviceWithNumString] hasPrefix:@"iPhone"]&&[[[self deviceWithNumString] stringByReplacingOccurrencesOfString:@"iPhone" withString:@""] floatValue]<40) {
        return;
    }
    if ([[self deviceWithNumString] hasPrefix:@"iPod"]&&[[[self deviceWithNumString] stringByReplacingOccurrencesOfString:@"iPod" withString:@""] floatValue]<40) {
        return;
    }
    if ([[self deviceWithNumString] hasPrefix:@"iPad"]&&[[[self deviceWithNumString] stringByReplacingOccurrencesOfString:@"iPad" withString:@""] floatValue]<25) {
        return;
    }
    
    CGFloat shadowW;
    switch (direction)
    {
        case RMoveDirectionLeft:
            shadowW = 2.0f;
            break;
        case RMoveDirectionRight:
            shadowW = -2.0f;
            break;
        default:
            break;
    }
    _mainContentView.layer.shadowOffset = CGSizeMake(shadowW, 1.0);
    _mainContentView.layer.shadowColor = [UIColor blackColor].CGColor;
    _mainContentView.layer.shadowOpacity = 0.8f;
}


- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}

@end
